package org.sja.log2traffic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.LinkedList;

import org.sja.log2traffic.dataStructures.ConfigurationEntity;
import org.sja.log2traffic.dataStructures.ProcessingStatusEntity;


public class LogLineProvider implements ILogLineProvider {

	private File[] directories;
	private LinkedList<File> fileToView = new LinkedList<File>();
	private BufferedReader bufferedReader;

	public LogLineProvider() {
	}

	@Override
	public void init(final ConfigurationEntity configuration, ProcessingStatusEntity processingStatusEntity) {
		directories = configuration.getInputDirectories();
		for (File dir : directories){
			String[] list = dir.list(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					if (name.startsWith(configuration.getLogFileNameStartWith())){
						return true;
					}
					return false;
				}
			});
			for (String fileStr : list){
				fileToView.add(new File(dir.getAbsolutePath() + "/" + fileStr));
			}
		}
		processingStatusEntity.setInitilFilesAmountToProcess(fileToView.size());
	}

	@Override
	public String readLine(ProcessingStatusEntity processingStatusEntity) {
		try {
			String readLine = null;
			do {
				if (bufferedReader == null) {
					File nextFile = null;
					if (fileToView.size() > 0) {
						nextFile = fileToView.removeFirst();
						processingStatusEntity.setFilesAmountToProcess(fileToView.size());
					} else {
						return null;
					}
					bufferedReader = new BufferedReader(new FileReader(nextFile));
				}
				readLine = bufferedReader.readLine();
				if (readLine == null){
					bufferedReader.close();
					bufferedReader = null;
				}
			} while (readLine == null);
			return readLine;
		} catch (Exception e) {
			e.printStackTrace();
			if (bufferedReader != null){
				try {
					bufferedReader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			return null;
		}
	}
}
